﻿using Blogger.UI.Models;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage.Table.DataServices;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;


namespace Blogger.UI.Data
{
    public class BloggerContext : TableServiceContext
    {
        public const string BlogSetName = "Blogs";
        public const string PostingSetName = "Postings";
        public const string RatingSetName = "Ratings";
        public const string CommentSetName = "Comments";

        CloudTableClient _client = null;
        public List<Exception> Errors { get; set; }
        public BloggerContext(CloudTableClient client)
            : base(client)
        {
            _client = client;
            Errors = new List<Exception>();
        }
        public void CreateIfNotExists()
        {
            var tables = new string[] { BlogSetName, PostingSetName, RatingSetName, CommentSetName };
            tables.ToList().ForEach(tableName =>
            {
                Task createTask = Task.Factory.StartNew(() =>
                {
                    try
                    {
                        var table = _client.GetTableReference(tableName);
                        table.CreateIfNotExists();
                    }
                    catch (Exception azureEx)
                    {
                        Errors.Add(azureEx);
                    }
                });
            });
        }
        public IQueryable<Blog> Blogs
        {
            get
            {
                return CreateQuery<Blog>(BlogSetName);
            }
        }
        public IQueryable<Posting> Postings
        {
            get
            {
                return CreateQuery<Posting>(PostingSetName);
            }
        }
        public IQueryable<Rating> Ratings
        {
            get
            {
                return CreateQuery<Rating>(RatingSetName);
            }
        }
        public IQueryable<Comment> Comments
        {
            get
            {
                return CreateQuery<Comment>(CommentSetName);
            }
        }
        public void AddObject(Blog blog)
        {
            this.AddObject(BlogSetName, blog);
        }
        public void AddObject(Posting post)
        {
            this.AddObject(PostingSetName, post);
        }
        public void AddObject(Comment comment)
        {
            this.AddObject(CommentSetName, comment);
        }
        public void AddObject(Rating rate)
        {
            this.AddObject(RatingSetName, rate);
        }
    }
}
